<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 *
 * @abstract 物料管理
 * @author zxj
 *
 */
class Material extends MY_Controller
{
    private $t_material = 'material_list';  //物料表

    function __construct()
    {
        parent::__construct();
        $this->load->model('procurement_model');
        //加载模型
        $this->load->model('product_model');
        $this->load->model('brand_model');
        $this->load->model('fault_model');
        $this->load->model('part_model');
        $this->load->model('fujian_model');
        $this->load->model('material_model');
        $this->load->model('order_model');
        $this->load->model('sort_model');
        $this->load->model('imei_model');
    }


    /**
     * 物料列表
     */
    function index()
    {
        //获取表单数据
        $data = $formField = gp();
        /**
         * 搜索逻辑处理
         */
        $where = $whereLike = array();
        //获取表字段(即查询条件,时间查询额外处理)
        $fieldsList = $this->db->list_fields($this->t_material);
        $fieldsList[] = 'startTime';
        $fieldsList[] = 'endTime';

        //需要模糊查询的字段
        $likeAry = array('name', 'sku','material_type');
        //拼接查询字符串
        $searchStr = 'products/material/index/?';
        foreach ($formField as $key => $val) {
            if (empty($val) || !in_array($key, $fieldsList)) continue;
            if (in_array($key, $likeAry)) {
                $whereLike[$key] = $val;
            } elseif ($key == 'startTime') {
                $where['add_time >'] = $val;
            } elseif ($key == 'endTime') {
                $where['add_time <'] = $val;
            } else {
                $where[$key] = $val;
            }
            $searchStr .= $key . '=' . $val . '&';
        }
        $searchStr = rtrim($searchStr, '&');
        //分页
        $this->load->library('pagination');
        $config['page_query_string'] = TRUE;
        $config['base_url'] = blang_url($searchStr);
        $config['total_rows'] = $this->common_model->countRows($this->t_material, $where, '', $whereLike);
        $config['per_page'] = 20;
        $config['uri_segment'] = config_item('enable_lang') ? 5 : 4;
        $page = max(1, intval($data['page']));
        $slimit = ($page - 1) * $config['per_page'];
        $this->pagination->initialize($config);
        $data['show_pages'] = $this->pagination->create_links();
        $num_page = ceil($config['total_rows'] / $config['per_page']);
        $data['show_params'] = "总共{$config['total_rows']}条记录   {$config['per_page']}条/页   当前第{$page}/{$num_page}页";
        //查询
        $datalist = $this->common_model->select($this->t_material, $slimit, $config['per_page'], 'add_time desc', $where, '', $whereLike);
        //重构数据
        foreach ($datalist as $key => &$vary) {

        }
        unset($vary);
        $data['dataList'] = $datalist;
        //导出数据
        $data['outputUrl'] = blang_url($searchStr . '&outputExcel=true&page=' . $data['page']);
        $outputExcel = gp('outputExcel');  //是否导出
        if ($outputExcel) {
            $fieldData = array(
                'name' => '名称', 'material_type' => '类型', 'sku' => 'SKU',
                'price' => '价格(USD)', 'cost' => '成本价(RMB)', 'add_time' => '创建时间'
            );
            excel_output('配件列表', $fieldData, $datalist);
        } else {
            //视图以及样式
            $this->load->view('defaults/material_index', $data);
            $this->load->view('defaults/common/footer');
        }
    }
    /**
     * 添加配件
     */
    public function addmaterial(){
        $addsuju=gp();
        $pid=$page = $this->uri->segment(5);
        $mtid=$page = $this->uri->segment(6);
        $addsuju['name_cn']=$addsuju['pingpai'].' '.$addsuju['xinghao'].' '.$addsuju['yanse'].' '.$addsuju['name_cn'];
        $arr=array(
            'sku'=>$addsuju['sku'],
            'name_cn'=>$addsuju['name_cn'],
            'number'=>$addsuju['number'],
            'mt_site'=>$addsuju['mt_site'],
            'addname'=>$addsuju['addname'],
            'price'=>$addsuju['accessory_price'],
            'accessory_cost'=>$addsuju['accessory_cost'],
            'pid'=>$pid,
            'order_id'=>$mtid,
            'addtime'=>time(),
        );
        $ids=$this->procurement_model->addmaterialpcm($arr);
        $addsuju['pcmid']=$ids;
        $this->peijian($pid,$addsuju);
        $dataArr = array(
            'id' => $ids,
            'order_id' => $mtid,
            'sku' => $addsuju['sku'],
            'name_cn' => $addsuju['name_cn'],
            'number' => $addsuju['number'],
            'addname' => $addsuju['addname'],
            'addtime' => time(),
            'price' => $addsuju['accessory_price'],
            'mt_site' => $addsuju['mt_site'],
            'accessory_cost' => $addsuju['accessory_cost']
        );
        $this->PostDataErp($dataArr);
        js_goto(blang_url('products/product/peijian/' . $pid.'/'.$mtid));
    }

    /**
     * 传输数据到ERP
     * @param $data
     */
    public function PostDataErp($dataArr){
        $siteURL = 'http://stock.dhhtgroup.com/webService/GetPurchaseRequirement.php';
        $data = array('account'=>'tomrepair', 'token'=>'tomrepairAccessoryPurshase','data'=>json_encode($dataArr));
        $str=CurlPost($siteURL,$data);
        return $str;
    }
    /**
     * 因需求变动创建的批量改变数据库数据的临时方法 需删除 防止被他人利用
     */
    public function upmt($type=''){
        $sss666=$this->procurement_model->ssslele();
        foreach($sss666 as $row) {
            if($row['pid']!='') {
                if($type=='add') {
                    $wuliaoList = $this->material_model->get_wuliao('', $row['pid']);
                    if (!$wuliaoList || $row['pid'] == $wuliaoList[0]['pid']) {
                        $arr = array(
                            'sku' => $row['sku'],
                            'name_cn' => $row['name_cn'],
                            'number' => $row['number'],
                            'mt_site' => $row['mt_site'],
                            'addname' => $row['addname'],
                            'price'=>$row['price'],
                            'accessory_cost'=>$row['accessory_cost'],
                            'pid' => $row['pid'],
                            'order_id' => $row['order_id'],
                            'addtime' => $row['addtime'],
                        );
                        $this->peijian($row['pid'], $arr);
                    }
                }elseif($type=='upd'){
                    if($row['price']=='') {
                        $wuliaoList = $this->material_model->get_wuliao('', '',substr_replace($row['sku'],'sku',0,3));
                        //获取订单信息
                        $orderFirst = $this->order_model->getOrderData($row['order_id']);
                        //根据订单查询维修站点货币
                        $repairSite = $this->order_model->getRepiarSiteData($orderFirst['repair_site_id']);
                        //当前维修站点货币种类
                        $accessoryCurrency = $repairSite['price_sort'];
                        //获取汇率
                        $rateRs = $this->common_model->selectFirst('exchange_rate', array('code' => $accessoryCurrency));
                        if (!$rateRs) {
                            show_error('获取费率失败,新增配件失败!');
                        }
                        $accessoryPrice = floatval($wuliaoList['price'] / $rateRs['value']);
                        $this->procurement_model->updatepcm($row['id'],array('price'=>$accessoryPrice,'accessory_cost'=>$wuliaoList['cost']));
                    }
                }elseif($type=='updpcmid'){
                    //$wuliaoList = $this->material_model->get_wuliao('', $row['pid']);
                    $this->material_model->updatepcmid($row['pid'],$row['sku'],$row['id']);
                }
            }
        }
        //更新报价单物料费用
        if($type=='count') {
            $sss666=$this->procurement_model->ssslele('','pid');
            foreach($sss666 as $s6) {
                if($s6['pid'] !='') {
                    $accSum_price = 0;
                    $wuliaoList = $this->material_model->get_wuliao('', $s6['pid']);
                    if($wuliaoList) {
                        foreach ($wuliaoList as $rs) {
                            $accSum_price += intval($rs['accessory_quantity']) * floatval($rs['accessory_price']);
                        }
                        $cpPriceData['accessory_price'] = $accSum_price;
                        $cpPriceData['pid'] = $s6['pid'];
                        $cpPriceData['oid'] = $s6['order_id'];
                        $this->product_model->setProductPrice($s6['pid'], $cpPriceData,$s6['addname']);
                    }
                }
            }
        }
    }
    /**
     * 采购列表
     */
    public function mtcglist($page=''){
        $gp=gp();
        $gp['page']?$gp['page']=$gp['page']:$gp['page']=1;
        $urlParameter='?mt_site='.$gp['mt_site'].'&status='.$gp['status'].'&keyword='.$gp['keyword'].'&startTime='.$gp['startTime'].'&endTime='.$gp['endTime'];
        $gp['startTime']=strtotime($gp['startTime']);
        $gp['endTime']=strtotime($gp['endTime']);
        $zt=$gp['status'];
        if($gp['status']=='qb'){
            $zt='';
        }
        $keyword='';
        if($gp['keyword']) {
            $keyword = array(
                'name_cn' => $gp['keyword'],
                'addname' => $gp['keyword'],
                'sku' => $gp['keyword'],
                'order_id'=> $gp['keyword'],
            );
        }
        $this->load->library('pagination');
        $config['page_query_string'] = TRUE;
        $config['base_url'] = blang_url('products/material/mtcglist'.$urlParameter);
        $config['total_rows'] = $this->procurement_model->CountRowPcm($gp['mt_site'],$zt,$keyword,$gp['startTime'],$gp['endTime']);
        $config['uri_segment'] = config_item('enable_lang')?5:4;
        $config['per_page'] = 20;
        $this->pagination->initialize($config);
        $data['pageshow']= $this->pagination->create_links();
        $data['mtlist']= $this->procurement_model->mtpcmlist($this->users['name'],$gp['mt_site'],$zt,$keyword,$gp['startTime'],$gp['endTime'],$config['per_page'],($gp['page']-1)*$config['per_page']);
        $data['gj']=$this->procurement_model->selectCustom('mt_repair_site');
        $data['mt_site']=$gp['mt_site'];
        $data['status']=$gp['status'];
        $data['urlParameter']=$urlParameter;
        $this->load->view('defaults/mtcg_list',$data);
        $this->load->view('defaults/common/footer');
    }
    /**
     * 取消数据
     * @param $id
     */
    public function scmtpcm($id){
        if(!$id) return '';
//        $pjFirst = $this->common_model->selectFirst('maintain_accessory',array('pcmid'=>$id));
//        //加上库存
//        if($pjFirst){
//            $wlkcData = array('quantity'=>'quantity+'.$pjFirst['accessory_quantity']);
//            $this->common_model->updateset('material_list',$wlkcData,array('id'=>$pjFirst['wid']));
//            $this->material_model->del_wuliao('','',$id);
//            //更新报价单物料费用
//            $accSum_price = '0';
//            $wuliaoList = $this->material_model->get_wuliao('', $pid);
//            foreach ($wuliaoList as $rs) {
//                $accSum_price += intval($rs['accessory_quantity'])*floatval($rs['accessory_price']);
//            }
//            $cpPriceData['accessory_price'] = $accSum_price;
//            $this->product_model->setProductPrice($pid,$cpPriceData);
//        }
        $data=array(
            'status'=>'5'
        );
        $this->procurement_model->updatepcm($id,$data);
        $url = 'http://stock.dhhtgroup.com/webService/cancelAccessoryPurchaseOrder.php';
        $dataArray = array('account'=>'tomrepair', 'token'=>'tomrepairAccessoryPurshase','data'=>$id);
        $result=CurlPost($url,$dataArray);
        $this->mtcglist();
    }

    /**
     * 导出excel
     */
    public function ExportPurchaseData(){
        $gp=gp();
        $keyword='';
        if($gp['keyword']) {
            $keyword = array(
                'name_cn' => $gp['keyword'],
                'addname' => $gp['keyword'],
                'sku' => $gp['keyword'],
                'order_id'=> $gp['keyword'],
            );
        }
        $purchaseData=$this->procurement_model->ExportPurchaseData($gp['mt_site'],$gp['status'],$keyword,$gp['startTime'],$gp['endTime']);
        foreach($purchaseData as &$row){
            $row['addtime']=date('Y-m-d H:i:s',$row['addtime']);
        }
        unset($row);
        $fieldData = array(
            'order_id'=>'order_id',
            'sku'=>'sku',
            'name_cn'=>'name_cn',
            'number'=>'number',
            'mt_site'=>'mt_site',
            'addname'=>'addname',
            'pid'=>'pid',
            'addtime'=>'addtime',
            'status'=>'status',
        );
        excel_output('PurchaseData',$fieldData,$purchaseData);
    }
    /**
     * 配件管理
     * @param string $pid
     * @return string
     */
    function peijian($pid = '',$d='')
    {
        //表单处理
        $data['post_type'] = __FUNCTION__;
        if($d) {
            $peijianData = $d;//数据保存
            $peijianData['accessory_quantity']=$peijianData['number'];
            $peijianData['accessory_name']=$peijianData['name_cn'];
            if($peijianData['addtime']) {
                $peijianData['purchase_time'] = $peijianData['addtime'];
            }
            if($peijianData['addname'] !='') {
                $peijianData['add_user'] = $peijianData['addname'];
            }
            if($peijianData['accessory_price']=='') {
                $peijianData['accessory_price'] = $peijianData['price'];
            }
        }else{
            $peijianData = gp();//数据保存
        }
        $pid = empty($pid) ? $peijianData['pid'] : intval($pid);
        $peijianData['pid'] = $pid;
        $data['peijianData'] = $peijianData;
        $mtid=$peijianData['wxdh'];
        //获取产品信息
        $productFirst = $this->product_model->get_product($pid);
        //插入数据
        //获取订单信息
        $orderFirst = $this->order_model->getOrderData($productFirst['maintain_id']);
        //根据订单查询维修站点货币
        $repairSite = $this->order_model->getRepiarSiteData($orderFirst['repair_site_id']);
        //当前维修站点货币种类
        $accessoryCurrency = $repairSite['price_sort'];
        //获取汇率
        $rateRs = $this->common_model->selectFirst('exchange_rate', array('code' => $accessoryCurrency));
        if (!$rateRs) {
            show_error('获取费率失败,新增配件失败!');
        }
        $accessoryPrice = floatval($peijianData['accessory_price'] / $rateRs['value']);
        $peijianData['accessory_currency'] = $accessoryCurrency;
        $peijianData['accessory_price'] = $accessoryPrice;
        $rsid = $this->material_model->addProductWuliao($peijianData,$peijianData['add_user']);
        if ($rsid && $peijianData['wid']) {
            //减去库存
            $wlkcData = array('quantity' => 'quantity-' . $peijianData['accessory_quantity']);
            $this->common_model->updateset('material_list', $wlkcData, array('id' => $peijianData['wid']));
            //更新报价单物料费用
            $accSum_price = 0;
            $wuliaoList = $this->material_model->get_wuliao('', $pid);
            foreach ($wuliaoList as $rs) {
                $accSum_price += intval($rs['accessory_quantity']) * floatval($rs['accessory_price']);
            }
            $cpPriceData['accessory_price'] = $accSum_price;
            $cpPriceData['pid'] = $pid;
            $cpPriceData['oid'] = $productFirst['maintain_id'];
            $this->product_model->setProductPrice($pid, $cpPriceData);
        }
    }
}
